package top.wilsonlv.jaguar.cloud.websocket.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import top.wilsonlv.jaguar.cloud.websocket.config.WebsocketConfig;
import top.wilsonlv.jaguar.cloud.websocket.handler.WebsocketOnlineHandler;
import top.wilsonlv.jaguar.cloud.websocket.sdk.dto.MessagePushTopic;
import top.wilsonlv.jaguar.cloud.websocket.wrapper.WebsocketSessionWrapper;
import top.wilsonlv.jaguar.commons.activemq.ActivemqConstant;

import static top.wilsonlv.jaguar.cloud.websocket.sdk.WebsocketConstant.DESTINATION_WEBSOCKET_PUSH2SESSION;
import static top.wilsonlv.jaguar.cloud.websocket.sdk.WebsocketConstant.DESTINATION_WEBSOCKET_PUSH2USER;

/**
 * @author lvws
 * @since 2021/6/22
 */
@Slf4j
@Component
public class WebsocketMessagePushListener {

    @JmsListener(destination = DESTINATION_WEBSOCKET_PUSH2USER, containerFactory = ActivemqConstant.TOPIC_LISTENER)
    public void listenUser(MessagePushTopic topic) {
        if (!WebsocketConfig.SERVER_INSTANCE_ID.equals(topic.getServerInstanceId())) {
            return;
        }

        WebsocketSessionWrapper session = WebsocketOnlineHandler.getSession(topic.getSessionId());
        session.sendMessage(topic.getMessage());
    }

    @JmsListener(destination = DESTINATION_WEBSOCKET_PUSH2SESSION, containerFactory = ActivemqConstant.TOPIC_LISTENER)
    public void listenSession(MessagePushTopic topic) {
        WebsocketSessionWrapper session = WebsocketOnlineHandler.getSession(topic.getSessionId());
        if (session != null) {
            session.sendMessage(topic.getMessage());
        }
    }

}
